package com.blog.util;

import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** 
 * @author ant 
 * @date 创建时间：2017年5月31日 上午9:45:05  
 */
public class PictureUtil {
	
	public static String changeSrc(String content,List<String> imgPath) {
    	Pattern patternImg = Pattern.compile("<(img|IMG)(.*?)(/>|></img>|>)");
        Matcher matcherImg = patternImg.matcher(content);
        boolean result = matcherImg.find();
        while (result) {
            //获取到匹配的<img />标签中的内容
            String stringImg = matcherImg.group(2);
            //开始匹配<img />标签中的src
            Pattern patternSrc = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
            Matcher matcherSrc = patternSrc.matcher(stringImg);
            if (matcherSrc.find()) {
                String stringSrc = matcherSrc.group(3);
                String fileName = stringSrc.substring(stringSrc.lastIndexOf("/")+1);
                Iterator<String> iterator = imgPath.iterator();
                while (iterator.hasNext()) {
					String url = iterator.next();
					if (url.contains(fileName)) {
						content = content.replace(stringSrc, url);
					}						
				}
            }
            //匹配content中是否存在下一个<img />标签，有则继续以上步骤匹配<img />标签中的src
            result = matcherImg.find();
        }
        return content;
	}
}
